home *** CD-ROM | disk | FTP | other *** search
- Path: news.compuserve.com!newsmaster
- From: RossBoylan@aol.com (Ross Boylan)
- Newsgroups: comp.lang.c++
- Subject: Mutually referring header files
- Date: Tue, 09 Apr 1996 19:22:49 GMT
- Organization: CompuServe Incorporated
- Message-ID: <4ked7q$8g3@dub-news-svc-1.compuserve.com>
- NNTP-Posting-Host: ad06-115.compuserve.com
- X-Newsreader: Forte Free Agent 1.0.82
-
- I have 2 classes A + B, defined in separate files. Each refers to and
- messages the other. What is the best way to handle this?
-
- 1) My naive approach was
- a.h----------------------------------------------------------
- #ifndef ah
- #define ah
- #include "b.h:
- class A {
- public:
- void hello();
- private:
- B *pB;
- //etc
- };
- #endif
-
- b.h------------------------------------------------------------
- #ifndef bh
- #define bh
- #include "a.h"
- class B{
- public:
- void hello();
- private:
- A *pA;
- };
- #endif
- -------------------------------------------------------------------
- The #ifndef's prevent infinite recursion, but if we start with
- #include "a.h"
- this will then include "b.h"
- b.h will skip a.h since the symbol ah is already defined.
- So when we get to the line A *pA in b.h, A has not yet been defined
- and we get an error.
-
- 2) My less naive approach was to add the declaration
- class A;
- to b.h. This works, but seems awfully obscure, since on the face of
- it the code
- "include a.h"
- class A;
- is redundant.
- Also when you multiply this by a bunch of classes referencing each
- other, it gets pretty messy. In particular if you add a subclass of A
- to the a.h file, and then want to refer to it from elsewhere, you must
- add the declaration for this class to all the consumers.
-
-
- 3) It may or may not matter that I'm actually using smart pointers, so
- the pointer declarations are actually
- CountedObjPtr<A> pA;
-
- 4)
- Also, I put no code definition in the header file (i.e., b.h contains
- no lines of the form
- class B {
- void doit() {pA->hello();};
- };
- Such lines require more than class A;--they must actually know the
- protocols A responds to.
-
- This bit of code discipline is possible for regular classes, but what
- do I do for templates. With my compiler (MSVC++ 4.0) the header file
- must include all the code definition.
-
-